package com.tianhe.common.tongsuo;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.Map;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class CryptoInterceptor implements Interceptor {

    @Autowired
    private SM3JNI sm3JNI;

    @Autowired
    private SM4JNI sm4JNI;

    // 默认密钥和IV（生产环境应从KMS获取）
    private static final String DEFAULT_SM4_KEY = "0123456789ABCDEF";
    private static final String DEFAULT_SM4_IV = "iv1234567890abc!";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object parameter = args[1];

        if (parameter != null) {
            processEncryption(parameter);
        }

        return invocation.proceed();
    }

    private void processEncryption(Object obj) throws IllegalAccessException {
        if (obj == null) return;

        // 处理实体类
        if (!isPrimitiveOrWrapper(obj.getClass())) {
            for (Field field : obj.getClass().getDeclaredFields()) {
                if (field.isAnnotationPresent(Tongsuo.class)) {
                    field.setAccessible(true);
                    Object value = field.get(obj);
                    if (value instanceof String) {
                        field.set(obj, encryptField((String) value, field.getAnnotation(Tongsuo.class)));
                    }
                }
            }
        }

        // 处理Map参数
        if (obj instanceof Map) {
            for (Object value : ((Map<?, ?>) obj).values()) {
                if (value != null && !isPrimitiveOrWrapper(value.getClass())) {
                    processEncryption(value);
                }
            }
        }
    }

    private String encryptField(String value, Tongsuo crypto) {
        if (value == null) return null;

        switch (crypto.algorithm()) {
            case SM3:
                return sm3JNI.sm3DigestHex(value);
            case SM4_CBC:
                return sm4JNI.cbcEncrypt(DEFAULT_SM4_IV, value);
            case SM4_ECB:
                return value;
            default:
                throw new IllegalArgumentException("不支持的加密算法: " + crypto.algorithm());
        }
    }

//    private String getKey(Tongsuo crypto) {
//        // 实际项目应从KMS根据keyAlias获取密钥
//        return crypto.keyAlias().isEmpty() ? DEFAULT_SM4_KEY : getKeyFromKMS(crypto.keyAlias());
//    }

    private boolean isPrimitiveOrWrapper(Class<?> clazz) {
        return clazz.isPrimitive() ||
                clazz.equals(String.class) ||
                Number.class.isAssignableFrom(clazz) ||
                clazz.equals(Boolean.class);
    }
}
